package com.minglead.crawler.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.minglead.crawler.base.ActionResponse;
import com.minglead.crawler.constant.YqCrawlerConstant;
import com.minglead.crawler.entity.*;
import com.minglead.crawler.enums.CrawlerGlobalKeyYesOrNoEnum;
import com.minglead.crawler.enums.CrawlerStateEnum;
import com.minglead.crawler.exception.BizCommonException;
import com.minglead.crawler.feign.PriceFeignClient;
import com.minglead.crawler.filter.YqCrawlerFilter;
import com.minglead.crawler.mapper.YqCrawlerMapper;
import com.minglead.crawler.service.*;
import com.minglead.crawler.util.FileUtils;
import com.minglead.crawler.util.PageUtils;
import com.minglead.crawler.util.MergeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/**
 * @description: 舆情爬虫配置表serviceImpl
 * @author: bxh
 * @date: 2024-8-1
 **/
@Service
public class YqCrawlerServiceImpl extends ServiceImpl<YqCrawlerMapper, YqCrawlerEntity> implements YqCrawlerService {

    @Autowired
    private YqBasicInfoService yqBasicInfoService;
    @Autowired
    private YqBasicInfoDetailService yqBasicInfoDetailService;
    @Autowired
    private DcDataMacroIndicatorDataService dcDataMacroIndicatorDataService;
    @Autowired
    private DcDataBigmercGrabLogService dcDataBigmercGrabLogService;

    @Override
    public IPage<YqCrawlerEntity> listPage(YqCrawlerFilter filter) {
        // 分页条件
        Page<YqCrawlerEntity> page = PageUtils.getPage(filter.getPage(), filter.getPageSize());
        //创建queryWrapper
        LambdaQueryWrapper<YqCrawlerEntity> queryWrapper = new LambdaQueryWrapper<>();
        // 按创建时间倒序排序
        queryWrapper.orderByDesc(YqCrawlerEntity::getCreatorTime);
        IPage<YqCrawlerEntity> webPage = super.page(page, queryWrapper);
        List<YqCrawlerEntity> list = webPage.getRecords();
//        for (YqCrawlerEntity entity : list) {
//            this.wrapEntity(entity);
//        }
        return webPage;
    }

    @Override
    public ActionResponse getLogById(String id) {
        YqCrawlerEntity entity = getById(id);
        if(entity == null){
            throw new BizCommonException("无效配置ID");
        }
        if(ObjectUtil.isEmpty(entity.getLogFile())){
            throw new BizCommonException("无效日志记录");
        }
        File logFile = new File(entity.getLogFile());
        if(!logFile.exists() || !logFile.isFile()){
            throw new BizCommonException("找不到有效日志");
        }
//        String dirPath = String.join("/", YqCrawlerConstant.CRAWLER_ROOT_PATH, entity.getKeyValue());
//        File mediaDir = new File(dirPath);
//        File[] dirList = mediaDir.listFiles(File::isDirectory);
//        if(dirList == null || dirList.length == 0){
//            throw new BizCommonException("找不到日志目录");
//        }
//        List<Date> dateList = Arrays.stream(dirList).map(dir -> getValidTime(dir.getName()))
//                .filter(Objects::nonNull).collect(Collectors.toList());
//        if(dateList.isEmpty()){
//            throw new BizCommonException("找不到有效日志目录");
//        }
//        Date latestDate = Collections.max(dateList);
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
//        String latestLogPath = String.join("/", dirPath, sdf.format(latestDate), "log.txt");
//        File logFile = new File(latestLogPath);
//        if(!logFile.exists() || !logFile.isFile()){
//            throw new BizCommonException("找不到有效日志");
//        }
        return ActionResponse.newInstanceOK("查询成功", FileUtils.getFileContent(logFile));
    }

    @Override
    public ActionResponse updateGlobalKeyword(String content) {
        try {
            if(ObjectUtil.isEmpty(content)){
                throw new BizCommonException("全局关键词不能为空");
            }
            content = FileUtils.cleanXSS(content);
            FileUtils.writeFileContent(YqCrawlerConstant.CRAWLER_GLOBAL_KEYWORD, content, false);
        } catch (Exception e) {
            throw new BizCommonException(e.getMessage());
        }
        return ActionResponse.newInstanceOK("更新成功", null);
    }

    @Override
    public ActionResponse updateKeyword(YqCrawlerEntity entity) {
        if(ObjectUtil.isEmpty(entity.getId())){
            throw new BizCommonException("无效配置");
        }
        if(ObjectUtil.isEmpty(entity.getKeyWord())){
            throw new BizCommonException("关键词不能为空");
        }
        if(ObjectUtil.isNull(entity.getGlobalKeyWord())){
            throw new BizCommonException("全局关键词使用状态不能为空");
        }
        CrawlerGlobalKeyYesOrNoEnum global = CrawlerGlobalKeyYesOrNoEnum.getEnum(entity.getGlobalKeyWord().toString());
        if(global == null){
            throw new BizCommonException("无效全局关键词使用状态");
        }
        YqCrawlerEntity oldEntity = this.getById(entity.getId());
        if(oldEntity == null){
            throw new BizCommonException("找不到有效配置");
        }
        oldEntity.setKeyWord(entity.getKeyWord());
        oldEntity.setGlobalKeyWord(entity.getGlobalKeyWord());
        oldEntity.setLastModifyTime(new Date());
        if(!this.updateById(oldEntity)){
            throw new BizCommonException("更新失败");
        }
        return ActionResponse.newInstanceOK("更新成功！", oldEntity);
    }

    @Override
    public ActionResponse startCrawlerById(String id) {
        YqCrawlerEntity entity = this.getById(id);
        if(entity == null){
            throw new BizCommonException("找不到有效配置");
        }
        if(entity.getState().toString().equals(CrawlerStateEnum.RUNNING.getCode())){
            throw new BizCommonException("爬虫已经启动");
        }
        Date date = MergeUtil.getCurrentDateTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String jobPath = String.join("/", YqCrawlerConstant.CRAWLER_ROOT_PATH, entity.getKeyValue(), sdf.format(date));
        String logPath = jobPath + "/log.txt";
        if(!new File(jobPath).mkdirs()){
            throw new BizCommonException("创建任务目录异常");
        }
        // 启动爬虫
        entity.setRunTimes(entity.getRunTimes() + 1);
        entity.setLastRunTime(MergeUtil.getCurrentDateTime());
        entity.setCurrentRecords(0);
        entity.setState(Integer.parseInt(CrawlerStateEnum.RUNNING.getCode()));
        entity.setLogFile(logPath);
        entity.setLastModifyTime(new Date());
        if(!this.updateById(entity)){
            throw new BizCommonException("更新失败！");
        }
        return ActionResponse.newInstanceOK("启动完成！", entity);
    }

    @Override
    public ActionResponse stopCrawlerById(String id) {
        YqCrawlerEntity entity = this.getById(id);
        if(entity == null){
            throw new BizCommonException("找不到有效配置");
        }
        // 停止爬虫，不停止当前正在执行的爬虫程序
        entity.setState(Integer.parseInt(CrawlerStateEnum.STOPPED.getCode()));
        entity.setLastModifyTime(new Date());
        if(!this.updateById(entity)){
            throw new BizCommonException("更新状态失败！");
        }
        return ActionResponse.newInstanceOK("停止完成！", entity);
    }

    @Override
    public ActionResponse saveCrawlerMedia(YqCrawlerEntity entity) {
        entity.setCreatorTime(new Date());
        if(!this.save(entity)){
            throw new BizCommonException("保存失败！");
        }
        return ActionResponse.newInstanceOK("保存成功！", entity);
    }

    @Override
    public ActionResponse getBasicInfo(String date) {
        if(ObjectUtil.isEmpty(date)){
            throw new BizCommonException("日期不能为空");
        }
        return ActionResponse.newInstanceOK("成功！", yqBasicInfoService.list(new LambdaQueryWrapper<YqBasicInfoEntity>().gt(YqBasicInfoEntity::getCreatorTime, date)));
    }

    @Override
    public ActionResponse getBasicInfoDetail(String date) {
        if(ObjectUtil.isEmpty(date)){
            throw new BizCommonException("日期不能为空");
        }
        return ActionResponse.newInstanceOK("成功！", yqBasicInfoDetailService.list(new LambdaQueryWrapper<YqBasicInfoDetailEntity>().gt(YqBasicInfoDetailEntity::getCreatorTime, date)));
    }

    @Override
    public ActionResponse getDataMacroIndicatorData(String date) {
        if(ObjectUtil.isEmpty(date)){
            throw new BizCommonException("日期不能为空");
        }
        return ActionResponse.newInstanceOK("成功！", dcDataMacroIndicatorDataService.list(new LambdaQueryWrapper<DcDataMacroIndicatorDataEntity>().gt(DcDataMacroIndicatorDataEntity::getCreatorTime, date)));
    }

    @Override
    public ActionResponse getDataBigmercGrabLog(String date) {
        if(ObjectUtil.isEmpty(date)){
            throw new BizCommonException("日期不能为空");
        }
        return ActionResponse.newInstanceOK("成功！", dcDataBigmercGrabLogService.list(new LambdaQueryWrapper<DcDataGrabLogEntity>().gt(DcDataGrabLogEntity::getCreatorTime, date)));
    }
}
